//
// Created by korack on 25-5-20.
//

#include "MsgQueue.h"

#include "Tools.h"

typedef struct _QueueNode QueueNode;
struct _QueueNode
{
        char       buf[50];
        QueueNode *next;
};

struct _MsgQueue
{
        QueueNode *head;
        QueueNode *tail;
        uint8_t    node_index;
        uint8_t    node_count;
};

static bool      is_inited = false;
static MsgQueue  global_msg_queue;
static QueueNode node[10];

MsgQueue *
msg_queue_new_from_global(void)
{
        if (is_inited)
                return &global_msg_queue;

        for (int i = 0; i < 10; i++) {
                node[i].buf[0] = '\0';
                node[i].next   = NULL;
        }

        global_msg_queue.head       = NULL;
        global_msg_queue.tail       = NULL;
        global_msg_queue.node_index = 0;
        global_msg_queue.node_count = 0;

        is_inited                   = true;
        return &global_msg_queue;
}

void
msg_queue_add_to_queue(MsgQueue *self, uint8_t *msg)
{
        if (self->node_count >= 10)
                return;

        if (self->tail == NULL) {
                self->tail = &node[self->node_index];
                self->head = self->tail;
        } else {
                self->tail->next = &node[self->node_index];
                self->tail       = self->tail->next;
        }

        strcpy_b(self->tail->buf, (const char *)msg, 49);
        self->tail->buf[49] = '\0';

        self->node_count += 1;
        if (self->node_index >= 10)
                self->node_index = 0;
}

uint8_t *
msg_queue_get_from_queue(MsgQueue *self)
{
        if (self->node_count == 0)
                return NULL;

        if (self->head == NULL)
                return NULL;

        uint8_t *msg = self->head->buf;
        self->head = self->head->next;

        self->node_count -= 1;
        return msg;
}
